package com.zhanghp.class05;

import com.zhanghp.refer.TreeNode;

/**
 * <h1>二叉树遍历</h1>
 *
 * @author zhanghp
 * @since 2024/1/9 16:12
 */
public class TraversalBinaryTree {
    public static void main(String[] args) {
        TreeNode head = new TreeNode(1);
        head.left = new TreeNode(2);
        head.right = new TreeNode(3);
        head.left.left = new TreeNode(4);
        head.left.right = new TreeNode(5);
        head.right.left = new TreeNode(6);
        head.right.right = new TreeNode(7);

        preorder(head);
        System.out.println("========");
        inorder(head);
        System.out.println("========");
        postorder(head);
        System.out.println("========");

    }

    /**
     * 先序遍历
     *
     * @param p {@link TreeNode}
     */
    public static void preorder(TreeNode p){
        if (p == null) {
            return;
        }
        System.out.println(p.val);
        preorder(p.left);
        preorder(p.right);

    }

    /**
     * 中序遍历
     *
     * @param p {@link TreeNode}
     */
    public static void inorder(TreeNode p){
        if (p == null) {
            return;
        }
        inorder(p.left);
        System.out.println(p.val);
        inorder(p.right);
    }

    /**
     * 后序遍历
     *
     * @param p {@link TreeNode}
     */
    public static void postorder(TreeNode p){
        if (p == null) {
            return;
        }
        postorder(p.left);
        postorder(p.right);
        System.out.println(p.val);
    }
}
